<template>
    <div class="user">
        <el-card>
            <div style="display: flex; align-items: center; margin-bottom: 20px;">
                <el-input
                    v-model="searchForm.nameOrId"
                    placeholder="请输入姓名/工号/学号查询"
                    style="margin-right: 10px; width: 300px;"
                ></el-input>
                <el-button type="primary" @click="onSearch">查询</el-button>
                <el-button type="success" @click="onAddUser" style="margin-left: auto;">+ 添加成员</el-button>
            </div>
            <el-table :data="tableData" border style="width: 100%">
                <el-table-column prop="index" label="序号" width="60"></el-table-column>
                <el-table-column prop="name" label="姓名" width="120"></el-table-column>
                <el-table-column prop="id" label="学号/工号" width="150"></el-table-column>
                <el-table-column prop="role" label="职位" width="100"></el-table-column>
                <el-table-column prop="department" label="院系" width="180"></el-table-column>
                <el-table-column prop="class_name" label="班级" width="180"></el-table-column>
                <el-table-column prop="info" label="处分信息" width="180"></el-table-column>
                <el-table-column label="处分状态" width="120">
                    <template #default="scope">
                        <el-tag
                            :type="scope.row.status === '未解除' ? 'success' : 'danger'"
                        >{{ scope.row.status }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                    <template #default="scope">
                        <el-button
                            type="text"
                            size="small"
                            @click="onEdit(scope.row)"
                        >修改</el-button>
                        <el-button
                            type="text"
                            size="small"
                            style="color: red;"
                            @click="onDelete(scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
  style="margin-top: 20px;"
  background
  :current-page="page.current"
  :page-size="page.size"
  layout="total, sizes, prev, pager, next"
  :total="page.total"
  @current-change="onCurrentChange"
  @size-change="onSizeChange"
></el-pagination>

        </el-card>
        <el-dialog :title="userTitle" v-model="userVisible" width="50%">
            <el-form :model="userForm" :rules="rules" ref="userRuleForm" label-width="120px">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="userForm.name" placeholder="请输入姓名"></el-input>
                </el-form-item>
                <el-form-item label="学号/工号" prop="id">
                    <el-input v-model="userForm.id" placeholder="请输入学号/工号"></el-input>
                </el-form-item>
                <el-form-item label="职位" prop="role">
                    <el-select v-model="userForm.role" placeholder="请选择职位">
                        <el-option label="教授" value="教授"></el-option>
                        <el-option label="学生" value="学生"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="院系" prop="department">
                    <el-input v-model="userForm.department" placeholder="请输入院系"></el-input>
                </el-form-item>
                <el-form-item label="班级" prop="class_name">
                    <el-input v-model="userForm.class_name" placeholder="请输入班级"></el-input>
                </el-form-item>
                <el-form-item label="处分信息" prop="info">
                    <el-select v-model="userForm.info" placeholder="请选择处分类型">
                        <el-option label="警告" value="警告"></el-option>
                        <el-option label="严重警告" value="严重警告"></el-option>
                        <el-option label="记过" value="记过"></el-option>
                        <el-option label="留校察看" value="留校察看"></el-option>
                        <el-option label="开除学籍" value="开除学籍"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="处分状态" prop="status">
                    <el-radio-group v-model="userForm.status">
                        <el-radio label="未解除">未解除</el-radio>
                        <el-radio label="已解除">已解除</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="userVisible = false">取消</el-button>
                <el-button type="primary" @click="onSubmit">提交</el-button>
            </template>
        </el-dialog>
    </div>
</template>


<script setup>
import {reactive, ref, onMounted, toRefs, computed} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";
import {useUserStore} from "@/store/settings.js";

const API_URL = "http://localhost:8080/api/users";

const userRuleForm = ref(null);

const myStore = useUserStore();
let user;
user = myStore.getUser
const state = reactive({
  searchForm: {
    nameOrId: null, // 查询条件：姓名或学号/工号
  },
  loading: false,
  page: {
    current: 1,
    size: 10,
    total: 0,
  },
  tableData: [],
  userVisible: false,
  userTitle: "添加成员",
  userForm: {
    name: "",
    id: "", // 学号/工号，用户手动填写
    role: "",
    department: "",
    class_name: "",
    info: "警告", // 默认处分类型
    status: "未解除", // 默认处分状态

  },
  rules: {
    name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
    id: [{ required: true, message: "请输入学号/工号", trigger: "blur" }],
    role: [{ required: true, message: "请选择职位", trigger: "change" }],
    department: [{ required: true, message: "请输入院系", trigger: "blur" }],
    class_name: [{ required: true, message: "请输入班级", trigger: "blur" }],
    info: [{ required: true, message: "请选择处分信息", trigger: "change" }],
    status: [{ required: true, message: "请选择处分状态", trigger: "change" }],
  },
});

const { searchForm, page, tableData, userVisible, userTitle, userForm } = toRefs(state);

// Fetch users from the backend
const fetchUsers = async () => {
  try {
    console.log("111", searchForm.value.nameOrId)
    // 获取后端返回的所有数据
    const response = await axios.get(`${API_URL}/search`, {
      params: {
        nameOrId: searchForm.value.nameOrId || '', // 查询条件
      },
    });

    // 全量数据
    const allData = response.data;

    // 计算分页数据
    const start = (page.value.current - 1) * page.value.size; // 当前页的起始索引
    const end = start + page.value.size; // 当前页的结束索引
    const paginatedData = allData.slice(start, end); // 截取当前页数据

    // 更新表格数据
    state.tableData = paginatedData.map((user, index) => ({
      index: start + index + 1, // 序号计算
      ...user,
    }));

    // 更新总记录数
    state.page.total = allData.length; // 总记录数
  } catch (error) {
    ElMessage.error("获取数据失败");
  } finally {
    state.loading = false; // 关闭加载状态
  }
};

const onCurrentChange = (currentPage) => {
  state.page.current = currentPage;
  fetchUsers(); // 刷新数据
};

const onSizeChange = (pageSize) => {
  state.page.size = pageSize;
  state.page.current = 1; // 重置到第一页
  fetchUsers(); // 刷新数据
};
const type = user.type;

// Add a new user
const addUser = async (user) => {
  if (type!==0){
    ElMessage.error("权限不够");
    return
  }
  try {
    if (type === 0) {
       const response = await axios.post(`${API_URL}/addjiLue`, user);
       // await axios.post(API_URL, {operator: user.username || '', type: "添加成员", color: 0, name: state});
        fetchUsers(); // Refresh table
        ElMessage.success("添加成功");
        state.userVisible = false;
    }else {
      ElMessage.error("权限不够");
    }

  } catch (error) {
    ElMessage.error("添加失败(学号重复)");
  }
};

// Update an existing user
const updateUser = async (id, user) => {
  if (type!==0){
    ElMessage.error("权限不够");
    return
  }
  try {
    if (type === 0) {
        const response = await axios.put(`${API_URL}/${id}`, user);
        fetchUsers(); // Refresh table
        ElMessage.success("修改成功");
        state.userVisible = false;
    }else {
      ElMessage.error("权限不够");
    }


  } catch (error) {
    ElMessage.error("修改失败");
  }
};

// Delete a user
const deleteUser = async (id) => {
  if (type!==0){
    ElMessage.error("权限不够");
    return
  }
  try {

    if (type === 0) {
       await axios.delete(`${API_URL}/${id}`);
      fetchUsers(); // Refresh table
      ElMessage.success("删除成功");
    }else {
      ElMessage.error("权限不够");
    }

  } catch (error) {
    ElMessage.error("删除失败");
  }
};

onMounted(() => {
  fetchUsers();
});

const onSearch = () => {
  fetchUsers();
};

const onAddUser = () => {
  if (type!==0){
    ElMessage.error("权限不够");
    return
  }
  state.userTitle = "添加成员";
  state.userForm = {
    name: "",
    id: "", // 学号/工号必须用户手动填写
    role: "",
    department: "",
    class_name: "",
    info: "警告", // 默认处分类型
    status: "未解除", // 默认处分状态
  };
  state.userVisible = true;
};

const onEdit = (row) => {
  if (type!==0){
    ElMessage.error("权限不够");
    return
  }
  state.userTitle = "修改成员";
  state.userForm = { ...row };
  state.userVisible = true;
};

const onDelete = (row) => {
  if (type!==0){
    ElMessage.error("权限不够");
    return
  }
  ElMessageBox.confirm(
    `确定要删除成员 ${row.name} 吗？`,
    "删除确认",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      deleteUser(row.id);
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const onSubmit = () => {
  if (type!==0){
    ElMessage.error("权限不够");
    return
  }
  userRuleForm.value.validate((valid) => {
    if (valid) {
      if (userTitle.value === "添加成员") {
        addUser(userForm.value);
      } else {
        updateUser(userForm.value.id, userForm.value);
      }
    }
  });
};
</script>


<style scoped>
.user {
  padding: 20px;
}
</style>
